package com.run.gogo.util;

import de.odysseus.el.ExpressionFactoryImpl;
import de.odysseus.el.util.SimpleContext;

import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import java.util.Map;

/**
 * rule 工具类
 * */
public class RuelUtil {

    private static final ExpressionFactory juelExpressionFactory = new ExpressionFactoryImpl();


    /**
     * 执行el 表达式
     * */
    public static Boolean execute(String cond, Map<String,Object> map,String ... keys){
        SimpleContext juelContext = new SimpleContext();
        if(null != keys && keys.length > 0){
            for (String key:keys){
                juelContext.setVariable(key, juelExpressionFactory.createValueExpression(map.get(key), map.get(key).getClass()));
            }
        }else{
            for (String k:map.keySet()){
                juelContext.setVariable(k, juelExpressionFactory.createValueExpression(map.get(k), map.get(k).getClass()));
            }
        }
        ValueExpression e = juelExpressionFactory.createValueExpression(juelContext, cond, Boolean.class);
        return (Boolean) e.getValue(juelContext);
    }

}
